<?php
/**
 * Author: dai
 * DateTime: 2016/11/15 17:54
 */
namespace App\Services;

/**
 * 微信服务类
 * Class WxService
 * @package App\Services
 */
class WxService
{

    /**
     * 微信文本消息模板
     * @var string
     */
    public static $textTpl = "<xml>
							<ToUserName><![CDATA[%s]]></ToUserName>
							<FromUserName><![CDATA[%s]]></FromUserName>
							<CreateTime>%s</CreateTime>
							<MsgType><![CDATA[%s]]></MsgType>
							<Content><![CDATA[%s]]></Content>
							<FuncFlag>0</FuncFlag>
							</xml>";

    /**
     *验证签名
     */
    public static function valid()
    {
        return self::checkSignature() ? true : false;
    }

    /**
     * 验证Signature
     * @return bool
     */
    public static function checkSignature()
    {
        // you must define TOKEN by yourself
        $signature = request()->input("signature");
        $timestamp = request()->input("timestamp");
        $nonce = request()->input("nonce");

        $token = config('wx.Token');
        if (!$token) {
            throw new Exception('TOKEN is not defined!');
        }
        $tmpArr = array($token, $timestamp, $nonce);
        // use SORT_STRING rule
        sort($tmpArr, SORT_STRING);
        $tmpStr = implode( $tmpArr );
        $tmpStr = sha1( $tmpStr );
        if( $tmpStr == $signature ){
            return true;
        }else{
            return false;
        }
    }

    /**
     * 获得微信主体消息
     * @return bool|\SimpleXMLElement
     */
    public static function postStr()
    {
        $postStr = file_get_contents('php://input');
        if (!empty($postStr)){
            /* libxml_disable_entity_loader is to prevent XML eXternal Entity Injection,
               the best way is to check the validity of xml by yourself */
            libxml_disable_entity_loader(true);
            $postObj = simplexml_load_string($postStr, 'SimpleXMLElement', LIBXML_NOCDATA);
            return $postObj;
        }
        return false;
    }

    /**
     * 文本消息发送
     * @param $postObj
     * @param $contentStr
     */
    public static function textMsg($postObj,$contentStr)
    {
        return sprintf(self::$textTpl, $postObj->FromUserName, $postObj->ToUserName, time(), 'text', $contentStr);
    }

}